from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse #返回ajax的数据的话需要先引入JsonResponse包
from .models import CCITUser
# Create your views here.

def index(request):
    return render(request, 'login_js.html')

def userLogin(request):
    result = {'status':'default',"content":"请求过来了"}
    if request.method == "POST": #判断提交的方式
        # 获取参数
        post_data = request.POST
        print(post_data)
        # return render(request, 'index.html')
        # return redirect(reverse('user:home'))
        if post_data:
            user = queryUser(post_data)
            if user: #找到用户
                if user.upwd == post_data['upwd']:
                    result['isUser'] = True
                    result['msg'] = '欢迎登陆'
                else:
                    result['isUser'] = False
                    result['msg'] = '密码错误'
            else:
                result['isUser'] = False
                result['msg'] = '用户名不存在，请联系系统管理员'  
            # user = querySetsUser(post_data)
            # if user:
            #     result['isUser'] = True
            #     result['msg'] = '欢迎登陆'
            # else:
            #     result['isUser'] = False
            #     result['msg'] = '用户名密码错误，请联系系统管理员'
    
        # result['data'] = post_data
        # result['msg'] = '请求Method不正确，请使用POST请求'
        # result['content'] = '服务器响应'
    else:
        result['msg'] = '请求Method不正确，请使用POST请求'
        result['content'] = '服务器响应'

    return JsonResponse(result)

def homePage(request):
    return render(request, 'index.html')

def test(request):
    users = getAllUser()
    if users:
        return JsonResponse({'msg': u'测试数据', 'users': users})
    else:
        print('no users')
    return JsonResponse({'msg': '测试数据'})

# 从数据库中读取用户列表
def getAllUser():
     # 获取所有用户
    all_users = CCITUser.objects.all()
    datas = []
    if all_users:
        for item in all_users:
            obj = {}
            obj['uID'] = item.uID
            obj['uname'] = item.uname
            obj['uemail'] = item.uemail
            # obj['regtime'] = item.uregisteredtime
            # print(dateToString(item.uregisteredtime))
            obj['regtime'] = dateToString(item.uregisteredtime)
            obj['ustatus'] = item.ustatus
            datas.append(obj)
        return datas
    else:
        return None

# 查询当前用户数据表中有没有当前用户
def queryUser(user):
    ##### 注意：下面是新手菜鸟写法，这种写法有一个问题
    ##### get()方法找到返回找到的一个对象，找不到则报异常，让程序挂掉
    # find_user = CCITUser.objects.get(uID=user['uname'])
    # if find_user:
    #     return find_user
    # else:
    #     return None
    #### 小牛的写法如下，使用try的方式 进行捕捉异常，这种方式程序不会挂掉
    try:
        # 正常下的操作
        find_user = CCITUser.objects.get(uID=user['uname'])
        return find_user
    except CCITUser.DoesNotExist: #异常下的操作，也就是找不到如何处理
        print(u'用户不存在')
    return None


# 多条件
def querySetsUser(user):
    sets = dict()
    sets['uID'] = user['uname']
    sets['upwd'] = user['upwd']
    find_user = CCITUser.objects.filter(**sets)
    if find_user:
        return find_user
    else:
        return None


# datetime 转字符串类型   
def dateToString(date): 
    ds = date.strftime('%Y-%m-%d %H:%M:%S') 
    return ds
# 将字符串时间格式 转换成 datatime格式
import datetime
def stringToDate(string): 
    #example '2013-07-22 09:44:15+00:00' 
    dt = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S+00:00") 
    #print dt 
    return dt 
